import time
from time import sleep
from helper import *

def login_xuexi(jy, username):
    link_index = "https://www.xuexi.cn"
    link_aliyun_oss_snrmyi = "https://snrmyi.oss-cn-hangzhou.aliyuncs.com/"
    link_login = "https://pc.xuexi.cn/points/login.html?ref=https://www.xuexi.cn/"
    el_exit = "//*[@id='root']/div/div[1]/header/div[2]/div[2]/span/a"
    el_iframe = '//*[@id="ddlogin-iframe"]'
    el_qrcode_img = '//img'
    remote = str(time.time()) + ".png"
    local = 'qrcode.png'
    tip01 = "同学:请将这个二维码截屏,然后尽快用<学习强国>扫码登录,超时二维码将失效,限时2分钟,但有可能失效时间更短!!"
    tip02 = "同学:扫码登录成功"
    tip03 = "同学:您在两分钟内未能完成扫码,无法正常登录您的强国帐号"
    # 打开主页
    jy.driver.get(link_index)
    sleep(5)
    # 读Cookie
    jy.readCookie()
    jy.driver.get(link_login)
    sleep(5)
    # 检查是否成功登录,是否有退出按钮
    if jy.getElementByXpath(el_exit) == None:
        # 不成功要扫码,将二维码保存到本地qrcode.png
        if jy.getIframeImgByXpath(el_iframe, el_qrcode_img, local):
            # 上传到阿里云oss
            oss2_upload(local, remote)
            # 发送二维码链接到钉钉,通知扫码
            dd_image(link_aliyun_oss_snrmyi + remote)
            dd_message(username + tip01)
        # 进行计时
        t_start = time.time()
        while jy.getElementByXpath(el_exit) == None:
            # 两分钟没有扫码就退出
            if time.time() - t_start > 120:
                dd_message(username + tip03)
                return False
        dd_message(username + tip02)
        jy.saveCookie()
    return True